
package com.wdf.dota;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.wdf.bean.Account;
import com.wdf.bean.ForumPosting;
import com.wdf.helper.DisplayUtils;
import com.wdf.helper.TimeUtils;
import com.wdf.rest.service.DotaDiscussionRestClient;

public class MyForumListActivity extends Activity {
	


	ProgressBar footLoading ;

	ListView listView;
	Button prevPageBtn;
	Button nextPageBtn;
	Button returnCommentBtn;

	
	LinearLayout pagnitationLinearLayout;
	
	TextView historyPageTv;
	

	List<ForumPosting> forumPostingList = new ArrayList<ForumPosting>(0); 

	String loginName;
	String contactName;
	ForumPostingRestService forumPostingRestService;

	private BaseAdapter adapter;
	private static final int STATUS_CHANGE = 0;
	
	public Handler mHandler;


	int pageNo =1;
	int pageSize = 10;
	int pageCount = 0;
	
	String accountId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_forum_posting_list);
		listView = (ListView) findViewById(android.R.id.list);

		footLoading =  (ProgressBar) findViewById(R.id.footLoading);
		
		prevPageBtn = (Button) findViewById(R.id.chat_prev_page);
		nextPageBtn = (Button) findViewById(R.id.chat_next_page);

		
		historyPageTv = (TextView) findViewById(R.id.history_page);
		historyPageTv = (TextView) findViewById(R.id.history_page);
		
		
		returnCommentBtn =  (Button) findViewById(R.id.return_comment);
		returnCommentBtn.setOnClickListener(returnCommentButtonListener);
		
		pagnitationLinearLayout =  (LinearLayout ) findViewById(R.id.pagnitation_linearLayout);
		
		SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
				Context.MODE_PRIVATE);
		accountId = sharedPreferences.getString("accountid", "0");

        forumPostingRestService = new ForumPostingRestService();

		updateTextView();
		prevPageBtn.setOnClickListener(prevPageButtonListener);
		nextPageBtn.setOnClickListener(nextPageButtonListener);
		
	

		adapter = new DiscussionListAdapter(MyForumListActivity.this);
		listView.setAdapter(adapter);

		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case STATUS_CHANGE:
					// 处理UI更新等操作
					updateUI();
				}
			};
		};
        
	//	forumPostingRestService.getForumPostings();

	}
	
	OnClickListener returnCommentButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			MyForumListActivity.this.finish();
		}
	};
	
	private boolean validateComment(String id){
		SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
				Context.MODE_PRIVATE);
	String key =  "-" + id;
	 int	times = sharedPreferences.getInt(key, 0);
	 if(times == 0){
		 return true;
	 }
	  Toast.makeText(this, "请勿重复评论!", 2).show();
		 return false;
	}

	private void updateUI() {
		pagnitationLinearLayout.setVisibility(View.VISIBLE);
		// 详细的更新
		adapter.notifyDataSetChanged();// 更新ListView
		updateTextView();
	}
	
	


	/**
	 * 更新页码
	 */
	private void updateTextView() {

		if (pageCount == 0) {
			historyPageTv.setText(0 + "/" + 0);
		} else {
			historyPageTv.setText(pageNo + "/"
					+ (pageCount/pageSize+1));
			
		}
		if(listView!=null && listView.getChildCount() >0){
		//	listView.requestFocusFromTouch();
			listView.setSelection(0);
		}
		
		if((pageCount/pageSize+1)<=1){
			pagnitationLinearLayout.setVisibility(View.GONE);
		}
	}

	public class DiscussionListAdapter extends BaseAdapter {

		private class RecentViewHolder {
			TextView postingIdView;
			TextView postingTopicView;
			TextView postingTitleView;
			TextView postingReviewtimesView;
			TextView postingContentView;
			TextView postingTimestampView;
			TextView repliesView;
			Button supporter;
		

		}

		Context context;
		LayoutInflater mInflater;

		public DiscussionListAdapter(Context context) {
			this.context = context;
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
		    return 	forumPostingList.size();
		}

		@Override
		public Object getItem(int position) {
			return forumPostingList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			RecentViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.forum_posting_item,
						null);
				holder = new RecentViewHolder();
				holder.postingIdView = (TextView) convertView.findViewById(R.id.posting_id);
				holder.postingTopicView = (TextView) convertView.findViewById(R.id.posting_topic);
				holder.postingTitleView = (TextView) convertView.findViewById(R.id.posting_title);
				holder.postingReviewtimesView = (TextView) convertView.findViewById(R.id.posting_reviewtimes);
				holder.postingContentView = (TextView) convertView.findViewById(R.id.posting_content);
				holder.postingTimestampView = (TextView) convertView.findViewById(R.id.posting_timestamp);
				holder.supporter = (Button)convertView.findViewById(R.id.supporter);
				holder.repliesView  = (TextView) convertView.findViewById(R.id.replies);
				
				convertView.setTag(holder);
			} else {
				holder = (RecentViewHolder) convertView.getTag();
			}
			final ForumPosting forumPosting = (ForumPosting)getItem(position);
			
			final String postingId =""+ forumPosting.getId();
			if (forumPosting != null) {
				holder.postingIdView.setText(""+forumPosting.getId());
				holder.postingTopicView.setText("["+forumPosting.getTopic()+"] ");
				holder.postingTitleView.setText(DisplayUtils.displayTitle(forumPosting.getTitle()));
				
				holder.postingContentView.setText(DisplayUtils.displayContent(forumPosting.getContent()));
				holder.postingReviewtimesView.setText("浏览("+forumPosting.getRead()+")");
				String name = "<font color=#484848 >"+forumPosting.getAccount().getUsername()+"</font>"+"" +TimeUtils.timePast(forumPosting.getCreatetime());
				holder.postingTimestampView.setText(Html.fromHtml(name));
				holder.supporter.setText("赞("+forumPosting.getSupporter()+")");
				holder.repliesView.setText("回复("+forumPosting.getReplies()+")");
				holder.postingTitleView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
					
							 Intent intent = new Intent(MyForumListActivity.this,
									 ForumViewActivity.class);
							 Bundle bundle = new Bundle();
							 bundle.putString("postingId", postingId);
							 bundle.putString("topic", forumPosting.getTopic());
							 bundle.putString("title", forumPosting.getTitle());
							 bundle.putString("content", forumPosting.getContent());
							 bundle.putString("author", forumPosting.getAccount().getUsername());
							 intent.putExtras(bundle);
				        	startActivityForResult(intent, 4);
						
					}
				});
				holder.postingContentView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
							 Intent intent = new Intent(MyForumListActivity.this,
									 ForumViewActivity.class);
							 Bundle bundle = new Bundle();
							 bundle.putString("postingId", postingId);
							 bundle.putString("topic", forumPosting.getTopic());
							 bundle.putString("title", forumPosting.getTitle());
							 bundle.putString("content", forumPosting.getContent());
							 bundle.putString("author", forumPosting.getAccount().getUsername());
							 intent.putExtras(bundle);
				        	startActivityForResult(intent, 4);
					
					}
				});
				
				holder.supporter.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if( validateComment(postingId)){
							forumPostingRestService.supportDiscussion(forumPosting.getTopic(),postingId);
						}
					}
				});
				convertView.setOnClickListener(
						new OnClickListener(){
							@Override
							public void onClick(View v) {
								 Intent intent = new Intent(MyForumListActivity.this,
										 ForumViewActivity.class);
								 Bundle bundle = new Bundle();
								 bundle.putString("postingId", postingId);
								 bundle.putString("topic", forumPosting.getTopic());
								 bundle.putString("title", forumPosting.getTitle());
								 bundle.putString("content", forumPosting.getContent());
								 bundle.putString("author", forumPosting.getAccount().getUsername());
								 intent.putExtras(bundle);
					        	startActivityForResult(intent, 4);
								
							}
				            }
						
						);

			}
			return convertView;
		}
	}

	/**
	 * 上一页按钮的监听事件
	 */
	OnClickListener prevPageButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (pageNo > 1) {
				pageNo=pageNo-1 ;
				reload();
			}

		}
	};

	/**
	 * 下一页按钮的监听事件
	 */
	OnClickListener nextPageButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (pageNo * pageSize < pageCount) {
				pageNo=	pageNo +1;
				reload();
			}

		}
	};



	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	            super.onActivityResult(requestCode, resultCode, data);
	            forumPostingRestService.getForumPostings();
	}
	
	@Override
	public void onResume() {
		forumPostingRestService.getForumPostings();
		super.onResume();
	}
	
	public void reload(){
	
		forumPostingList = new ArrayList<ForumPosting>(0); 
		adapter.notifyDataSetChanged();// 更新ListView
		updateTextView();
		forumPostingRestService.getForumPostings();
	}
	
	class ForumPostingRestService {
        
        
        public ForumPostingRestService(){
        	
        }
		
		 public  void  getForumPostings(){
			footLoading.setVisibility(View.VISIBLE);
			pagnitationLinearLayout.setVisibility(View.GONE);
			 String url = "/dota/forumpostings/user.json";
 			 final RequestParams params = new RequestParams();
			  params.put("accountId", accountId);
			  params.put("pageNo", ""+pageNo);
			  params.put("pageSize", ""+pageSize);
			 DotaDiscussionRestClient.get(url, params, new JsonHttpResponseHandler() {
				 
		            @Override
		            public void onSuccess(JSONObject response) {
		                try {
		                	if(response !=null){
		                	pageCount = response.getInt("total");
		                	pageNo =  response.getInt("pageNo");
		                	pageSize =  response.getInt("pageSize");
		                	JSONArray elements = response.getJSONArray("items");
		                	if(elements!=null){
		                	 List<ForumPosting> forumPostings = new ArrayList<ForumPosting>();
		                	 for(int i=0;i < elements.length();i++){
		                		 JSONObject object = elements.getJSONObject(i);
		                		 ForumPosting forumPosting = new ForumPosting();
		                		 JSONObject user  = object.getJSONObject("account");
		                		
		                		 forumPosting.setContent(object.getString("content"));
		                		 forumPosting.setCreatetime(object.getString("createtime"));
		                		 forumPosting.setId(object.getInt("id"));
		                		 forumPosting.setReplies(object.getInt("replies"));
		                		 forumPosting.setRead(object.getInt("reviewTimes"));
		                		 forumPosting.setProtester(object.getInt("protester"));
		                		 forumPosting.setSupporter(object.getInt("supporter"));
		                		 forumPosting.setTopic(object.getString("topic"));
		                		 forumPosting.setTitle(object.getString("title"));
		                		Account account = new Account();
		                		 account.setUsername(user.getString("username"));
		                		 account.setId(user.getInt("id"));
		                		 forumPosting.setAccount(account);
		                		 forumPostings.add(forumPosting);
		                	 }
		                	 forumPostingList = forumPostings;
		                	 updateUI();
		                	 footLoading.setVisibility(View.GONE);
		                	}
		                	}
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }finally{
		                	
		                }
		                
		            }
		            
		            @Override
		            public void onSuccess(JSONArray elements) {
		                try {
		                	if(elements!=null){
		                	 List<ForumPosting> forumPostings = new ArrayList<ForumPosting>();
		                	 for(int i=0;i < elements.length();i++){
		                		 JSONObject object = elements.getJSONObject(i);
		                		 ForumPosting forumPosting = new ForumPosting();
		                		 JSONObject user  = object.getJSONObject("account");
		                		
		                		 forumPosting.setContent(object.getString("content"));
		                		 forumPosting.setCreatetime(object.getString("createtime"));
		                		 forumPosting.setId(object.getInt("id"));
		                		 forumPosting.setReplies(object.getInt("replies"));
		                		 forumPosting.setRead(object.getInt("reviewTimes"));
		                		 forumPosting.setProtester(object.getInt("protester"));
		                		 forumPosting.setSupporter(object.getInt("supporter"));
		                		 forumPosting.setTopic(object.getString("topic"));
		                		 forumPosting.setTitle(object.getString("title"));
		                		Account account = new Account();
		                		 account.setUsername(user.getString("username"));
		                		 account.setId(user.getInt("id"));
		                		 forumPosting.setAccount(account);
		                		 forumPostings.add(forumPosting);
		                	 }
		                	 forumPostingList = forumPostings;
		                	 updateUI();
		                	 footLoading.setVisibility(View.GONE);
		                	}
		       
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }finally{
		                	
		                }
		                
		            }
		            
		            public void onFailure(Throwable error){
		            	 footLoading.setVisibility(View.GONE);
		            }
		        });

		 }
		 
		 

		 
		 public  void  supportDiscussion(final String topic,final String id){
	 			final RequestParams params = new RequestParams();
			//	 params.put("commentId", id);
	 			 footLoading.setVisibility(View.VISIBLE);
				 DotaDiscussionRestClient.put("/dota/forumpostings/support.json?postingId="+id, params, new JsonHttpResponseHandler() {
					 
			            @Override
			            public void onSuccess(JSONObject object) {
			            	SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
			        				Context.MODE_PRIVATE);
			            	Editor editor = sharedPreferences.edit();
			            	String key = topic +"-" + id;
			            	editor.putInt(key, 1);
			            	editor.commit();
			            	 forumPostingRestService.getForumPostings();
			            	 footLoading.setVisibility(View.GONE);
			            }
			            
			            public void onFailure(Throwable error){
			            	// footLoading.setVisibility(View.GONE);
			            }
			        });

			 }	

	}

}